<template>
  <div
    @click="
      () => {
        isDialogVisible = true;
      }
    "
  >
    报告路况
  </div>
  <!-- 创建对话框 -->
  <el-dialog
    v-model="isDialogVisible"
    width="500"
    title="报告路况"
    draggable
    :modal="false"
    append-to-body
    :destroy-on-close="true"
    @close="onCancel"
  >
    <el-form
      :model="form"
      label-width="100px"
      style="max-width: 500px"
      :rules="rules"
      ref="ruleFormRef"
    >
      <el-form-item label="事件类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择事件类型" clearable>
          <el-option label="碰撞" value="碰撞" />
          <el-option label="失火" value="失火" />
          <el-option label="碾压" value="碾压" />
          <el-option label="刮擦" value="刮擦" />
          <el-option label="翻车" value="翻车" />
          <el-option label="其他" value="其他" />
        </el-select>
      </el-form-item>
      <el-form-item label="事件地址" prop="address">
        <el-input
          v-model="form.address"
          placeholder="路况地址需包含市、区、事故路段及建筑或小区楼号"
          @blur="getRightAddress"
        />
      </el-form-item>
      <el-form-item prop="address_right">
        <el-input
          v-model="form.address_right"
          placeholder="将根据您填写的地址自动生成矫正后的地址信息"
          disabled
        />
      </el-form-item>
      <el-form-item label="建筑标识" prop="building">
        <el-input
          v-model="form.building"
          placeholder="请输入事故最近的建筑标识"
        />
      </el-form-item>
      <el-form-item label="发生时间" prop="time">
        <el-date-picker
          v-model="form.time"
          type="datetime"
          placeholder="请选择事故发生的具体时间"
          :shortcuts="shortcuts"
        />
      </el-form-item>
      <el-form-item label="事件描述" prop="discribe">
        <el-input v-model="form.discribe" placeholder="请输入事故的具体信息" />
      </el-form-item>
      <!-- <el-form-item label="处理状态">
        <el-select v-model="form.status">
          <el-option label="待处理" :value="'0'" />
          <el-option label="处理中" :value="'1'" />
          <el-option label="已归档" :value="'2'" />
        </el-select>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onSubmit(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="onReset(ruleFormRef)">重置</el-button>
        <el-button @click="onCancel">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage} from "element-plus";
// 格式化时间
import dayjs from 'dayjs';
import cloneDeep from 'lodash/cloneDeep';
import axios from "axios";
import { usePiniaStore } from "../../../../stores/pinia";
import { storeToRefs } from "pinia";
const piniaStore = usePiniaStore();
const { userReportData } = storeToRefs(piniaStore);
// console.log(userReportData.value);// []
// 表单校验
const ruleFormRef = ref();
let $map = null;
onMounted(() => {
  $map = inject("$map");
  // console.log($map);
});
// 创建 Axios 实例
const axios2 = axios.create({});
// 对话框的显隐
const isDialogVisible = ref(false);
// console.log(JSON.parse(localStorage.getItem('userInfo')).username)
// 获取普通用户名
const common_username = JSON.parse(localStorage.getItem("userInfo")).username;
const form = ref({
  id: +new Date(),
  common_username,
  type: "碰撞",
  address: "",
  address_right: "",
  // 坐标
  lnglat: "",
  building: "",
  time: new Date(),
  discribe: "",
  // 事件处理状态 默认为待处理
  status: "0",
  // 交警对用户上报的回应状态【0123待回应，忽略，通过】
  response: "0",
  // 是否已添加到地图【01】
  isAdd:'0'
});
// 时间选择器的dshortcuts
const shortcuts = [
  {
    text: "Today",
    value: new Date(),
  },
  {
    text: "Yesterday",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "A week ago",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];
// 表单校验规则
// 校验后的地址是否存在
const checkRtaddress = (rule, value, callback) => {
  if (!value) {
    return callback(new Error("地址信息为必填项"));
  }
  if (value === "找不到你输入的地址，请重新填写") {
    // console.log(value);
    callback(new Error("请填写准确的地址信息"));
  } else {
    callback();
  }
};
const rules = ref({
  type: [{ required: true, message: "时间类型为必选项", trigger: "blur" }],
  address: [
    { required: true, message: "地址为必填项", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  address_right: [
    { required: true, message: "找不到你填写的地址，请填写准确的地址信息" },
    { validator: checkRtaddress, trigger: "change" },
  ],
  building: [{ required: true, message: "建筑标识为必填项", trigger: "blur" }],
  time: [{ required: true, message: "发生时间为必选项", trigger: "blur" }],
  discribe: [{ required: true, message: "事件描述为必填项", trigger: "blur" }],
  // lngLat: [
  //   {
  //     validator: checkLngLat,
  //     trigger: "blur",
  //   },
  // ],
});
// 函数：根据用户填写的地址信息，发送axios请求
const getRightAddress = async () => {
  try {
    let res = await axios2.get(`https://restapi.amap.com/v3/geocode/geo`, {
      params: {
        key: "ebb10ca7243496314177e468a640a218",
        address: form.value.address,
      },
    });
    // console.log(res.data.geocodes[0]);
    // .formatted_address    // .location
    // console.log(res.data.status);
    if (res.data.status === "0") {
      form.value.address_right = "找不到你输入的地址，请重新填写";
      return;
    }
    if (res.data.geocodes[0]) {
      form.value.address_right = res.data.geocodes[0].formatted_address; // "湖北省武汉市江夏区武汉中地科技园"
      form.value.lnglat = res.data.geocodes[0].location.split(","); // ['114.407080','30.464390']
      $map.getView().animate({
        center: form.value.lnglat,
        zoom: 16,
        duration: 1000,
      });
    }
  } catch (err) {
    console.log(err);
  }
};
// 复位地图函数
const resetMap = () => {
  $map.getView().animate({
    center: [114.3694, 30.49],
    zoom: 13,
    duration: 1000,
  });
};
// 函数：重置表单
const onReset = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
// 函数：提交表单
const onSubmit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      form.value.id = +new Date();
      let form_clone = cloneDeep(form.value);
      // console.dir(form_clone.time);
      form_clone.time = dayjs(form_clone.time).format('YYYY-MM-DD HH:mm:ss')
      // console.dir(form_clone);
      // console.log(JSON.stringify(form_clone))
      userReportData.value.push(form_clone);
      // console.log(userReportData.value);
      // axios
      //   .post("src/stores/reportEvent.json", form.value)
      //   .then((response) => {
      //     console.log(form.value);
      //     console.log(response.data,response);
      //   })
      //   .catch((error) => {
      //     console.error("Error submitting data:", error);
      //   });
      onReset(ruleFormRef.value);
      // console.log(form.value, "reset");
      ElMessage({
          message: "提交成功",
          type: "success",
        });
      isDialogVisible.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 函数：取消表单
const onCancel = () => {
  // 复位地图
  resetMap();
  // 关闭对话框
  isDialogVisible.value = false;
};
</script>

<style lang="scss" scoped></style>
